<?php

namespace haibao\www\business\message;

use haibao\www\business\BusinessException;
use haibao\frame\data\query\Condition;
use haibao\www\model\data\message\MessageUser as MessageUserModel;
use haibao\www\model\data\message\MessageBoxUnReg as MessageBoxUnRegModel;
use haibao\www\model\data\message\MessageBox as MessageBoxModel;
use haibao\www\model\filter\message\MessageUser as MessageUserFilter;
use haibao\www\business\message\MessagePrivate as MessagePrivateBusiness;
class MessageUser extends \haibao\www\business\Base{
    
	private static $unUserSystemMessage = array(
		'亲，海报网欢迎你的到来！你现在所属游客身份，不过仍然可以发表评论哦！现在你可以<span class="name"><a href="http://user.haibao.com/login.html">快速登录</a></span>升级为高B格报友',
		/* '亲爱的报友，参与海报网用户调查，告诉海报君你的期望和意愿，有机会获赠小礼物1份。<a href="http://www.haibao.com/features/fashion/ilovehaibao/" target="_blank">[立即参与]</a>' */
	);
    public static function getLastSyncTimeByUserId($userId){
        $data = new \haibao\www\data\message\MessageUser();
        $user = $data->getMessageUserByUserId($userId);
        $lastSyncTime = $user['LastReadTime'];
        if(!$user){
            $userModel = new MessageUserModel;
            $userModel->UserId = $userId;
            $userModel->UnReadCommentCount = 0;
            $userModel->UnReadPrivateCount = 0;
            $userModel->UnReadSystemCount = 0;
            $userModel->LastReadTime = new \DateTime();
            $userModel->CreateTime = new \DateTime();
            $data->add($userModel);
        }
        return $lastSyncTime ? $lastSyncTime : date('Y-m-d H:i:s');
    }

	public static function getMessageUser(){
		$messageUser = array();
		$messageUserInfo = null;
		$userInfo = \haibao\comment\common\Auth::getUserInfo();
		if($userInfo){
			$messageUser = \haibao\www\cache\Message::getMessageUser($userInfo['_auth_user_id']);
			if(!$messageUser){
				if($userInfo['sso_user_public'] == \haibao\comment\common\Auth::SSO_USER_PUBLIC_USER){
					$messageUserInfo = self::getMessageUserFromDB($userInfo['_auth_user_id']);
				}
				$messageUser = self::initMessageUser($userInfo,$messageUserInfo,false);
				\haibao\www\cache\Message::setMessageUser($userInfo['_auth_user_id'],$messageUser);
			}
			$messageUser = json_decode($messageUser);
		}
		return $messageUser;
	}
	
	public static function updateMessageUser($userId,$messageType,$isTrueUser=true,$addNum=1){
		$messageUser = \haibao\www\cache\Message::getMessageUser($userId);
		$messageUserInfo = null;
		if($isTrueUser) $messageUserInfo = self::getMessageUserFromDB($userId);
		if(!$messageUser){
			$messageUser = self::packageMessageUser($userId,$isTrueUser,$messageType,$addNum,$messageUserInfo);
		}else{
			$messageUser = json_decode($messageUser,true);
			$messageUser = self::packageMessageUser($userId,$isTrueUser,$messageType,$addNum,$messageUserInfo,$messageUser);
		}
		\haibao\www\cache\Message::setMessageUser($userId,$messageUser);
	}
	public static function getMessageUserFromDB($userId){
		if(!isset($userId)){
			throw new BusinessException('用户ID不能为空');
		}
		
		usleep(1000);
		$filter = new MessageUserFilter();
		$filter->select(array(
			MessageUserFilter::CONDITION_FIELD_NAME_USERID,
			MessageUserFilter::CONDITION_FIELD_NAME_UNREAD_COMMENT_COUNT,
			MessageUserFilter::CONDITION_FIELD_NAME_UNREAD_PRIVATE_COUNT,
			MessageUserFilter::CONDITION_FIELD_NAME_UNREAD_SYSTEM_COUNT,
			MessageUserFilter::CONDITION_FIELD_NAME_LAST_READ_TIME
		));
		$filter->limit(0,1);
		$filter->where(MessageUserFilter::CONDITION_FIELD_NAME_USERID,Condition::CONDITION_EQUAL,(int)$userId);
		$data = new \haibao\www\data\message\MessageUser();
		$messageUserInfo = $data->getOne($filter);
		if(!$messageUserInfo){
			$messageUserInfo = new MessageUserModel;
			$messageUserInfo->UserId = $userId;
			$messageUserInfo->UnReadCommentCount = 0;
			$messageUserInfo->UnReadPrivateCount = 0;
			$messageUserInfo->UnReadSystemCount = 0;
			$messageUserInfo->LastReadTime = new \DateTime();
			$messageUserInfo->CreateTime = new \DateTime();
			$data->add($messageUserInfo);
		}
		return $messageUserInfo;
	}

	private static function initMessageUser($userInfo,$messageUserInfo=null,$filterPrivate=true){
		if($messageUserInfo){
			// DO : 获取用户私信未读数
			if($filterPrivate){
				$messageUserInfo->UnReadPrivateCount = MessagePrivateBusiness::getNewMessage($messageUserInfo->UserId);
			}
			$messageUser = array(
					'UserId'=>$messageUserInfo->UserId,
					'UserPublic'=>$userInfo['sso_user_public'],
					'UnReadCommentCount'=>$messageUserInfo->UnReadCommentCount,
					'UnReadPrivateCount'=>$messageUserInfo->UnReadPrivateCount,
					'UnReadSystemCount'=>$messageUserInfo->UnReadSystemCount,
					'MessageCount'=>$messageUserInfo->UnReadCommentCount+$messageUserInfo->UnReadPrivateCount+$messageUserInfo->UnReadSystemCount,
					'LastReadTime'=>$messageUserInfo->LastReadTime
			);
		}else{
			// DO : 推送给游客一条系统消息
			foreach(self::$unUserSystemMessage as $messageContent){
				self::addMessageInfoForSystem($userInfo,$messageContent,true,\haibao\www\model\data\message\MessageBox::READ_HAVE);
			}
			$messageUser = array(
					'UserId'=>$userInfo['_auth_user_id'],
					'UserPublic'=>$userInfo['sso_user_public'],
					'UnReadCommentCount'=>0,
					'MessageCount'=>0
			);
		}
		return json_encode($messageUser);
	}
	
	private static function packageMessageUser($userId,$isTrueUser=true,$messageType=\haibao\www\model\data\message\MessageBox::MESSAGE_COMMENT,$addNum=1,$messageUserInfo,$messageUser = array()){
		if($isTrueUser){
			$messageUser = array(
					'UserId'=>$messageUserInfo->UserId,
					'UserPublic'=>\haibao\comment\common\Auth::SSO_USER_PUBLIC_USER,
					'UnReadCommentCount'=>$messageUserInfo->UnReadCommentCount,
					'UnReadPrivateCount'=>$messageUserInfo->UnReadPrivateCount,
					'UnReadSystemCount'=>$messageUserInfo->UnReadSystemCount,
					'MessageCount'=>$messageUserInfo->UnReadCommentCount+$messageUserInfo->UnReadPrivateCount+$messageUserInfo->UnReadSystemCount,
					'LastReadTime'=>$messageUserInfo->LastReadTime
			);

			$filter = new MessageUserFilter();
			$filter->where(MessageUserFilter::CONDITION_FIELD_NAME_USERID,Condition::CONDITION_EQUAL,$userId);
			switch($messageType){
				case \haibao\www\model\data\message\MessageBox::MESSAGE_TYPE_COMMENT:
					$messageUserArr = array(
						MessageUserFilter::CONDITION_FIELD_NAME_UNREAD_COMMENT_COUNT => $messageUserInfo->UnReadCommentCount + $addNum,
					);
					$messageUser['UnReadCommentCount'] = $messageUserInfo->UnReadCommentCount + $addNum;
					if($messageUser['UnReadCommentCount'] < 0){
						$messageUser['UnReadCommentCount'] = 0;
					}
					if($addNum>0) $messageUser['MessageCount'] = $messageUser['MessageCount'] + $addNum;
					break;
				case \haibao\www\model\data\message\MessageBox::MESSAGE_TYPE_SYSTEM:
					$messageUserArr = array(
						MessageUserFilter::CONDITION_FIELD_NAME_UNREAD_SYSTEM_COUNT => $messageUserInfo->UnReadSystemCount + $addNum,
						MessageUserFilter::CONDITION_FIELD_NAME_LAST_READ_TIME => new \DateTime(),
					);
					$messageUser['UnReadSystemCount'] = $messageUserInfo->UnReadSystemCount + $addNum;
					if($messageUser['UnReadSystemCount'] < 0){
						$messageUser['UnReadSystemCount'] = 0;
					}
					if($addNum>0) $messageUser['MessageCount'] = $messageUser['MessageCount'] + $addNum;
					$messageUser['LastReadTime'] =  new \DateTime();
					break;
				case \haibao\www\model\data\message\MessageBox::MESSAGE_TYPE_PRIVATE:
					$messageUserArr = array(
					MessageUserFilter::CONDITION_FIELD_NAME_UNREAD_PRIVATE_COUNT => $messageUserInfo->UnReadPrivateCount + $addNum,
					MessageUserFilter::CONDITION_FIELD_NAME_LAST_READ_TIME => new \DateTime(),
					);
					$messageUser['UnReadPrivateCount'] = $messageUserInfo->UnReadPrivateCount + $addNum;
					if($messageUser['UnReadPrivateCount'] < 0){
						$messageUser['UnReadPrivateCount'] = 0;
					}
					if($addNum>0) $messageUser['MessageCount'] = $messageUser['MessageCount'] + $addNum;
					$messageUser['LastReadTime'] =  new \DateTime();
					break;				
				default:
					break;
			}
			$data = new \haibao\www\data\message\MessageUser();
			$messageUserInfo = $data->update($messageUserArr,$filter);
		}else{
			if(!$messageUser){
				$messageUser = array(
					'UserId'=>$userId,
					'UserPublic'=>\haibao\comment\common\Auth::SSO_USER_PUBLIC_UNREGUSER,
					'UnReadCommentCount'=>0,
					'MessageCount'=>0
				);
			}

			switch($messageType){
				case \haibao\www\model\data\message\MessageBox::MESSAGE_TYPE_COMMENT:
					$messageUser['UnReadCommentCount'] = $messageUser['UnReadCommentCount']+$addNum;
					if($addNum>0) $messageUser['MessageCount'] = $messageUser['MessageCount'] + $addNum;
					break;
				default:
					break;
			}
		}
		
		return json_encode($messageUser);
	}
	
	public static function addMessageInfoForSystem($userInfo,$messageContent = '',$isUnReg=true,$isRead=\haibao\www\model\data\message\MessageBox::READ_NOT){
		if($isUnReg){
			$messageBoxUnRegModel = new MessageBoxUnRegModel();
			$messageBoxUnRegModel->ToUserId = $userInfo['_auth_user_id'];
			$messageBoxUnRegModel->MessageType = \haibao\www\model\data\message\MessageBox::MESSAGE_TYPE_SYSTEM;
			$messageBoxUnRegModel->IsRead = $isRead;
			$messageData = array("IsTrueUser"=>false,"Title"=>"","Content"=>$messageContent);
			$messageBoxUnRegModel->MessageData = json_encode($messageData);
			$messageBoxUnRegModel->CreateTime = new \DateTime();
			$data = new \haibao\www\data\message\MessageBoxUnReg();
			$data->add($messageBoxUnRegModel);
		}else{
			$messageBoxModel = new MessageBoxModel();
			$messageBoxModel->ToUserId = $userInfo['_auth_user_id'];
			$messageBoxModel->MessageType = \haibao\www\model\data\message\MessageBox::MESSAGE_TYPE_SYSTEM;
			$messageBoxModel->IsRead = $isRead;
			$messageData = array("IsTrueUser"=>true,"Title"=>"","Content"=>$messageContent);
			$messageBoxModel->MessageData = json_encode($messageData);
			$messageBoxModel->CreateTime = new \DateTime();
			$data = new \haibao\www\data\message\MessageBox();
			$data->add($messageBoxModel);
		}
		return true;
	}
	
	public static function getMessageUserByUserId($userId){
		$messageUser = array();
		$messageUserInfo = null;
		$userInfo =  \haibao\user\business\User::getUserByUserId($userId);
		if($userInfo){
			$userInfo = $userInfo->toArray();
			$userInfo['sso_user_public'] = \haibao\comment\common\Auth::SSO_USER_PUBLIC_USER;
			$messageUser = \haibao\www\cache\Message::getMessageUser($userId);
			if(!$messageUser){
				$messageUserInfo = self::getMessageUserFromDB($userId);
				$messageUser = self::initMessageUser($userInfo,$messageUserInfo,false);
				\haibao\www\cache\Message::setMessageUser($userId,$messageUser);
			}
			$messageUser = json_decode($messageUser);
		}
		return $messageUser;
	}
}